package com.huya.controller.admin;


import com.huya.common.constant.JwtClaimsConstant;
import com.huya.common.properties.JwtProperties;
import com.huya.common.result.Result;
import com.huya.common.utils.JwtUtil;
import com.huya.pojo.dto.AdminLoginDTO;
import com.huya.pojo.entity.Admin;
import com.huya.pojo.vo.AdminLoginVO;
import com.huya.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/admin")
@Slf4j
public class AdminController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("adminLoginDTO: {}", adminLoginDTO);

        Admin admin = adminService.login(adminLoginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .id(admin.getId())
                .userName(admin.getUsername())
                .name(admin.getName())
                .token(token)
                .build();
        return Result.success(adminLoginVO);
    }


    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result<String>logout() {
        return Result.success();
    }
}
